'use strict';
// 打印当前环境信息
const db = uniCloud.database();
const dbCmd = db.command;
const tenantCollection = db.collection('tenants');
const miniappCollection = db.collection('tenant_miniapp');
const userCollection = db.collection('users');

exports.main = async (event, context) => {
  const { action, params, tenant_id, miniapp, status, tenant } = event;
  
  try {
    // 获取商户列表
    if (action === 'getTenants') {
      console.log('查询参数:', params);
      const page = params.page || 1;
      const pageSize = params.pageSize || 10;
      const keyword = params.keyword || '';
      const statusFilter = params.status !== undefined && !isNaN(parseInt(params.status)) 
        ? parseInt(params.status) 
        : '';
      
      let query = tenantCollection;
      let countQuery = tenantCollection;
      
      // 处理关键字搜索
      if (keyword) {
        console.log('使用关键字查询:', keyword);
        const whereCondition = dbCmd.or([
          { tenant_name: new RegExp(keyword, 'i') },
          { contact_name: new RegExp(keyword, 'i') },
          { contact_phone: new RegExp(keyword, 'i') }
        ]);
        query = query.where(whereCondition);
        countQuery = countQuery.where(whereCondition);
      }
      
      // 处理状态筛选
      if (statusFilter !== '') {
        console.log('使用状态筛选:', statusFilter);
        query = query.where({ status: statusFilter });
        countQuery = countQuery.where({ status: statusFilter });
      }
      
      // 简化查询，先获取总数
      const countResult = await countQuery.count();
      
      // 简化查询，分页获取数据
      const queryResult = await query
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .orderBy('created_at', 'desc')
        .get();
      
      console.log('查询结果数量:', queryResult.data.length);
      
      // 恢复小程序信息查询
      const tenantList = queryResult.data;
      const tenantIds = tenantList.map(item => item.tenant_id);
      
      if (tenantIds.length > 0) {
        const miniappResult = await miniappCollection.where({
          tenant_id: dbCmd.in(tenantIds)
        }).get();
        
        const miniappMap = {};
        miniappResult.data.forEach(item => {
          miniappMap[item.tenant_id] = item;
        });
        
        // 补充小程序信息
        const enhancedList = tenantList.map(tenant => {
          const miniapp = miniappMap[tenant.tenant_id];
          return {
            ...tenant,
            miniapp_status: miniapp ? (miniapp.status === 1) : false,
            appid: miniapp ? miniapp.appid : '',
            app_name: miniapp ? miniapp.app_name : ''
          };
        });
        
        return {
          code: 0,
          message: 'success',
          data: enhancedList,
          total: countResult.total
        };
      } else {
        return {
          code: 0,
          message: 'success',
          data: tenantList,
          total: countResult.total
        };
      }
    }
    
    // 添加商户
    if (action === 'addTenant') {
      console.log('添加商户参数:', tenant);
      
      // 验证必填参数
      if (!tenant.tenant_name || !tenant.contact_name || !tenant.contact_phone) {
        return {
          code: 400,
          message: '缺少必要参数'
        };
      }
      
      // 生成商户ID
      const tenantId = 'T' + Date.now().toString();
      const now = Date.now();
      
      // 创建商户数据对象
      const tenantData = {
        tenant_id: tenantId,
        tenant_name: tenant.tenant_name,
        contact_name: tenant.contact_name,
        contact_phone: tenant.contact_phone,
        contact_email: tenant.contact_email || '',
        address: tenant.address || '',
        description: tenant.description || '',
        status: 1,
        created_at: now,
        updated_at: now
      };
      
      // 新增商户
      const addResult = await tenantCollection.add(tenantData);
      
      // 可选：创建商户管理员账号
      try {
        const username = 'admin_' + tenantId.toLowerCase();
        
        // 检查用户名是否已存在
        const existingUser = await db.collection('uni-id-users').where({
          username: username
        }).get();
        
        if (existingUser.data.length === 0) {
          // 创建用户记录
          await db.collection('uni-id-users').add({
            username: username,
            password: '$2a$12$UVDppoqC.u6PHDcIwnLG5.yf5BBWe.FHOXj1Qn1KYCUc2KySc8JnK', // 123456加密后的值
            role: ['tenant_admin'],
            nickname: tenant.contact_name,
            mobile: tenant.contact_phone,
            email: tenant.contact_email || '',
            status: 1,
            tenant_id: tenantId,
            register_date: now
          });
          
          console.log('创建商户管理员账号成功:', username);
        }
      } catch (userError) {
        console.error('创建商户管理员账号失败:', userError);
        // 不中断主流程，仍然返回商户创建成功
      }
      
      return {
        code: 0,
        message: '添加商户成功',
        tenant_id: tenantId
      };
    }
    
    // 恢复更新商户状态功能
    if (action === 'updateTenantStatus') {
      if (!tenant_id || status === undefined) {
        return {
          code: 400,
          message: '参数错误'
        };
      }
      
      const result = await tenantCollection.where({
        tenant_id: tenant_id
      }).update({
        status: status,
        updated_at: Date.now()
      });
      
      return {
        code: 0,
        message: status === 1 ? '启用商户成功' : '禁用商户成功'
      };
    }
    
    // 恢复获取小程序配置功能
    if (action === 'getMiniappConfig') {
      if (!tenant_id) {
        return {
          code: 400,
          message: '参数错误'
        };
      }
      
      const result = await miniappCollection.where({
        tenant_id: tenant_id
      }).get();
      
      if (result.data.length > 0) {
        return {
          code: 0,
          message: 'success',
          data: result.data[0]
        };
      } else {
        return {
          code: 0,
          message: 'success',
          data: null
        };
      }
    }
    
    // 恢复保存小程序配置功能
    if (action === 'saveMiniappConfig') {
      if (!tenant_id || !miniapp) {
        return {
          code: 400,
          message: '参数错误'
        };
      }
      
      const now = Date.now();
      
      // 检查是否已存在
      const existingConfig = await miniappCollection.where({
        tenant_id: tenant_id
      }).get();
      
      if (existingConfig.data.length > 0) {
        // 更新
        await miniappCollection.where({
          tenant_id: tenant_id
        }).update({
          appid: miniapp.appid,
          app_name: miniapp.app_name,
          app_secret: miniapp.app_secret,
          status: 1,
          updated_at: now
        });
      } else {
        // 新增
        await miniappCollection.add({
          tenant_id: tenant_id,
          appid: miniapp.appid,
          app_name: miniapp.app_name,
          app_secret: miniapp.app_secret,
          status: 1,
          created_at: now,
          updated_at: now
        });
      }
      
      return {
        code: 0,
        message: '保存小程序配置成功'
      };
    }
    
    // 获取所有小程序授权列表 - 优化版本
    if (action === 'getAllMiniapps') {
      try {
        // 第一步：获取所有小程序配置
        const miniappsResult = await miniappCollection.get();
        const miniapps = miniappsResult.data || [];
        
        if (miniapps.length === 0) {
          return {
            code: 0,
            message: 'success',
            data: []
          };
        }
        
        // 第二步：获取所有相关商户信息
        const tenantIds = miniapps.map(item => item.tenant_id);
        const tenantsResult = await tenantCollection.where({
          tenant_id: dbCmd.in(tenantIds)
        }).field({
          tenant_id: 1,
          tenant_name: 1
        }).get();
        
        // 构建商户名称映射
        const tenantMap = {};
        tenantsResult.data.forEach(tenant => {
          tenantMap[tenant.tenant_id] = tenant.tenant_name;
        });
        
        // 手动合并数据
        const result = miniapps.map(miniapp => {
          return {
            ...miniapp,
            tenant_name: tenantMap[miniapp.tenant_id] || '未知商户'
          };
        });
        
        // 按创建时间排序
        result.sort((a, b) => (b.created_at || 0) - (a.created_at || 0));
        
        return {
          code: 0,
          message: 'success',
          data: result
        };
      } catch (error) {
        console.error('获取小程序列表出错:', error);
        return {
          code: 500,
          message: '获取小程序列表失败: ' + error.message
        };
      }
    }
    
    return {
      code: 400,
      message: '未知的操作类型'
    };
  } catch (error) {
    console.error('执行出错:', error);
    return {
      code: 500,
      message: '操作失败: ' + error.message
    };
  }
};